#include <stdio.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
char getbuf[1024];
int getlen;
int main(int argc, char **argv)
{
	int socketfd = 0;
	int count, count_;
	int packetsize = 0;
	struct sockaddr_in sock_s;
	struct sockaddr_in sock_c;
	socketfd = socket(AF_INET, SOCK_DGRAM, NULL);
	if (socketfd == -1) {
		printf("socket create failed!\n");
	}

	memset(&sock_s, 0, sizeof(sock_s));
	sock_s.sin_family=AF_INET;
	sock_s.sin_port=htons(9527);
	sock_s.sin_addr.s_addr=INADDR_ANY;
	bind(socketfd, (struct sockaddr*)&sock_s, sizeof(sock_s));
	count_ = count;
	while (1) {
		
		memset(getbuf, 0, 1024);
		if (recvfrom(socketfd, getbuf, sizeof(getbuf), 0, (struct sockaddr*)&sock_c, &getlen)) {
			//printf("getbuf:%s\n", getbuf);
		}
		sscanf(getbuf, "%d:%s", &count, getbuf);
		if (count == count_) 
			printf("again packet!\n");
		if ((count-count_) != 1)
			printf("lose packet!\n");
		printf("NO:%d\n", packetsize++);
		printf("get status:%d\nget data:%s\n", count-count_, getbuf);
		count_ = count;
		
		while (1) {
			memset(getbuf, 0, sizeof(getbuf));
			snprintf(getbuf, sizeof(getbuf) - 1, "%d:\n%s", count++, "nihao1");
			if (sendto(socketfd, getbuf, strlen(getbuf), 0, (struct sockaddr *)&sock_c, getlen)) {
				printf("send failed!%d\n", errno);
				close(socketfd);
				return -1;
			}
		}
	}
	close(socketfd);
	return 0;
}
